import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Select, Modal, Form, message, DatePicker } from 'antd';
import type { TableColumnsType } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import styles from './index.less';
import { getOrder, getPlanner, getDirectors, deleteOrder, distributionOrder, getCompany, outRequire } from '@/api/services';
import AddOrderModal from './components/AddOrderModal';


const OrderMangement: React.FC = () => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [data, setData] = useState([]);
    const [page, setPage] = useState<number>(1);
    const [total, setTotal] = useState(0);
    const [planners, setPlanners] = useState<any>([]);//生产计划员
    const [company, setCompany] = useState<any>([]);
    const [directors, setDirectors] = useState<any>([]);
    const [modalOpen, setModalOpen] = useState<boolean>(false);
    const [customerId, setCustomerId] = useState<any>('');
    const [plannerId, setPlannerId] = useState<any>('');
    const [directorId, setDirectorId] = useState<any>('');


    const getOrderList = () => {
        getOrder({
            page: page,
            size: 5,
            customerId: customerId ? customerId : '',
            plannerId: plannerId ? plannerId : '',
            directorId: directorId ? directorId : ''
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                setData(res.results);
                setTotal(res.length);
            }

        });
    }

    useEffect(() => {
        getOrderList();
    }, [page, customerId, plannerId, directorId]);

    //委派
    const handleSelectChange = (id: any, value: any) => {
        distributionOrder({
            orderId: id,
            plannerId: value
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                getOrderList();
                message.success('委派成功');
            }
        })
    }

    const handleChange = (pagination: any, filters: any, sorter: any) => {
        console.log(filters);
        const customerCompany = filters.customerCompany ? filters.customerCompany[0] : '';
        setCustomerId(customerCompany);
        const plannerName = filters.plannerName ? filters.plannerName[0] : '';
        setPlannerId(plannerName);
        const directorName = filters.directorName ? filters.directorName[0] : '';
        setDirectorId(directorName);
    };

    //提库
    const outWareHouse = (id: any, detail: any) => {
        outRequire({
            orderId: id,
            detail: detail
        }).then((res: any) => {
            if (res.status == 200) {
                message.success(res.msg);
                getOrderList();
            }
        })
    }

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    // const rowSelection = {
    //     selectedRowKeys,
    //     onChange: onSelectChange,
    // };
    const hasSelected = selectedRowKeys.length > 0;

    //生产计划员
    useEffect(() => {
        getPlanner().then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                const options = res.results.map((user: any) => ({
                    value: user.user_id,
                    label: user.user_name,
                }));
                setPlanners(options);
            }

        })
    }, [])

    //获取合作公司
    useEffect(() => {
        getCompany().then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                const options = res.results.map((goods: any) => ({
                    value: goods.customer_id,
                    label: goods.customer_company,
                }));
                setCompany(options);
            }

        })
    }, [])

    //获取经理列表
    useEffect(() => {
        getDirectors().then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                const options = res.results.map((goods: any) => ({
                    value: goods.user_id,
                    label: goods.user_name,
                }));
                setDirectors(options);
            }

        })
    }, [])


    //删除订单
    const delOrderList = (id: any) => {
        console.log('id', id);
        deleteOrder({
            id: id
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                message.success('删除成功');
                getOrderList();
            }

        })
    }


    const handleAddCancel = () => {
        setModalOpen(false);
    }

    const formatDetail = (data: any) => {
        var dataArray = data.split("||");
        var result = "";

        // 遍历数组中的每一对数据
        for (var i = 0; i < dataArray.length; i += 2) {
            // 获取物品名称和数量
            var item = dataArray[i].trim();
            var quantity = dataArray[i + 1].trim();

            // 格式化为键值对的形式，并添加到结果中
            result += item + "：" + quantity;

            // 如果不是最后一对数据，添加逗号分隔符
            if (i < dataArray.length - 2) {
                result += ", ";
            }
        }

        return result;
    }

    const paginationConfig = {
        total: total,
        onChange: (page: number, pageSize?: number) => {
            setPage(page);
        },
        showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
    }
    const columns = [
        {
            title: '合作公司',
            dataIndex: 'customerCompany',
            filters: company.map((user: any) => ({
                value: user.value,
                text: user.label
            })),
        },
        {
            title: '订单明细',
            dataIndex: 'order_detail',
            width: 150,
            render: (_: any, record: any) => (
                <div>
                    <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        {formatDetail(record.order_detail).split(',').map((item: any, index: number) => (
                            <span key={index}>{item}</span>
                        ))}
                    </Space>
                </div>
            )
        },
        {
            title: '订单金额',
            dataIndex: 'order_money',
        },
        {
            title: '订单状态',
            dataIndex: 'order_type'
        },
        {
            title: '订单提交时间',
            dataIndex: 'order_posttime',
        },
        {
            title: '订单完成截止时间',
            dataIndex: 'order_deadline',
        },

        {
            title: '生产计划员',
            dataIndex: 'plannerName',
            filters: planners.map((user: any) => ({
                value: user.value,
                text: user.label
            })),
            render: (_: any, record: any) => (
                <Select
                    style={{ width: 120 }}
                    onChange={(value) => handleSelectChange(record.order_id, value)}
                    value={record.plannerName}
                    options={planners}
                />
            )
        },
        {
            title: '负责经理',
            dataIndex: 'directorName',
            filters: directors.map((user: any) => ({
                value: user.value,
                text: user.label
            })),
        },
        {
            title: 'Action',
            dataIndex: '',
            key: 'x',
            render: (_: any, record: any) =>
                <Space size="middle">
                    {
                        record.order_type == '生产完成,待出库' ?
                            <a
                                onClick={() => outWareHouse(record.order_id, record.order_detail)}
                            >提库</a> :
                            <a
                                onClick={() => message.info('请等待生产员处理')}
                            >提库</a>
                    }

                    <a onClick={() => delOrderList(record.order_id)}>删除</a>
                </Space>
        },
    ];

    return (
        <div className={styles.orderContainer}>

            <div className={styles.header}>

                <Button type="primary" style={{ marginRight: 20 }}
                    onClick={() => {
                        setModalOpen(true);
                        // getProductList();
                        // form.resetFields();
                    }}
                >新增订单</Button>
            </div>
            <Table
                onChange={handleChange}
                pagination={paginationConfig}
                columns={columns} dataSource={data} />
            {modalOpen && <AddOrderModal onCancel={handleAddCancel} getOrderList={getOrderList} />}
        </div>
    );
};

export default OrderMangement;